package com.lau.controller;


import com.lau.common.annotation.OperationLog;
import com.lau.common.enums.OperationTypeEnum;
import com.lau.common.lang.Result;
import com.lau.entity.SysRole;
import com.lau.entity.SysRoleMenu;
import com.lau.entity.SysUserRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Lau
 * @since 2023-12-22
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {

    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/info/{id}")
    @OperationLog(event = "查询角色信息",operType = OperationTypeEnum.QUERY)
    public Result info(@PathVariable("id") Long id) {
        return Result.succ(sysRoleService.getSysRoleByRoleId(id));
    }

    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/list")
    @OperationLog(event = "查询角色列表",operType = OperationTypeEnum.QUERY)
    public Result list(Page page, String name) {
        return Result.succ(sysRoleService.pageRoles(page,name));
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:role:save')")
    @OperationLog(event = "新增角色",operType = OperationTypeEnum.ADD)
    public Result save(@Validated @RequestBody SysRole sysRole) {
        sysRoleService.save(sysRole);
        return Result.succ(sysRole);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:role:update')")
    @OperationLog(event = "更新角色",operType = OperationTypeEnum.UPDATE)
    public Result update(@Validated @RequestBody SysRole sysRole) {
        sysRoleService.updateById(sysRole);
        // 更新缓存
        sysUserService.clearUserAuthorityInfoByRoleId(sysRole.getId());
        return Result.succ(sysRole);
    }

    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:role:delete')")
    @Transactional
    @OperationLog(event = "删除角色",operType = OperationTypeEnum.DELETE)
    public Result info(@RequestBody Long[] ids) {
        sysRoleService.removeByIds(Arrays.asList(ids));

        // 删除中间表
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id", ids));
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("role_id", ids));

        // 缓存同步删除
        Arrays.stream(ids).forEach(id -> {
            // 更新缓存
            sysUserService.clearUserAuthorityInfoByRoleId(id);
        });

        return Result.succ("");
    }

    @Transactional
    @PostMapping("/perm/{roleId}")
    @PreAuthorize("hasAuthority('sys:role:perm')")
    @OperationLog(event = "更新角色权限",operType = OperationTypeEnum.UPDATE)
    public Result info(@PathVariable("roleId") Long roleId, @RequestBody Long[] menuIds) {

        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();

        Arrays.stream(menuIds).forEach(menuId -> {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleId);

            sysRoleMenus.add(roleMenu);
        });

        // 先删除原来的记录，再保存新的
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));
        sysRoleMenuService.saveBatch(sysRoleMenus);

        // 删除缓存
        sysUserService.clearUserAuthorityInfoByRoleId(roleId);

        return Result.succ(menuIds);
    }

}
